package com.community.web.user.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.community.common.exception.NeusoftException;
import com.community.common.login.LoginUserHolder;
import com.community.common.result.Result;
import com.community.common.result.ResultCodeEnum;
import com.community.model.entity.User;
import com.community.web.user.service.UserService;
import com.community.web.user.vo.UserInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Api(tags = "用户模块")
@RestController
@RequestMapping("/user/info")
public class UserController {

    @Autowired
    private UserService service;

    @ApiOperation("修改密码")
    @PostMapping("password")
    public Result updatePassword(@RequestBody String password){
        Long userId = LoginUserHolder.getLoginUser().getUserId();
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, userId);
        updateWrapper.ne(User::getUserStatus, 2);
        updateWrapper.set(User::getUserPassword, password);
        service.update(updateWrapper);
        return Result.ok();
    }

    @ApiOperation("用户信息")
    @GetMapping()
    public Result<User> getUserInfo(){
        Long userId = LoginUserHolder.getLoginUser().getUserId();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, userId);
        queryWrapper.ne(User::getUserStatus, 2);
        User user = service.getOne(queryWrapper);
        return Result.ok(user);
    }

    @ApiOperation("修改用户信息")
    @PutMapping()
    public Result updateUserInfo(@RequestBody User user){
        service.saveOrUpdate(user);
        return Result.ok();
    }

    @ApiOperation("根据手机号查询用户信息")
    @GetMapping("info")
    public Result<UserInfoVo> findUserInfo(@RequestParam String phone){
        Long userId = LoginUserHolder.getLoginUser().getUserId();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        queryWrapper.ne(User::getUserStatus, 2);
        User user = service.getOne(queryWrapper);
        if (user == null){
            throw new NeusoftException(ResultCodeEnum.USER_ACCOUNT_NOT_EXIST_ERROR);
        }
        if (user.getId() == userId.intValue()){
            throw new NeusoftException(ResultCodeEnum.SELF_ERROR);
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setUserName(user.getUserName());
        userInfoVo.setId(user.getId());
        userInfoVo.setPhone(user.getPhone());
        userInfoVo.setLastLoginTime(user.getLastLoginTime());
        return Result.ok(userInfoVo);
    }

}
